﻿using System;
using System.Collections.Generic;
using WorkLogger.Client.DataAccess.Model;
using WorkLogger.Client.DataAccess.Repository;

namespace WorkLogger.Client {
	public class WorkDayManager : IWorkDayManager {
		private readonly ISystemClock systemClock;
		private readonly IWorkDayRepository workDayRepository;
		private WorkDay currentWorkDay;

		public WorkDayManager(ISystemClock systemClock, IWorkDayRepository workDayRepository) {
			this.systemClock = systemClock;
			this.workDayRepository = workDayRepository;
		}

		public WorkDay GetCurrentWorkDay() {
			DateTime now = systemClock.Now;
			DateTime currentDay = now.Date;
			if (currentWorkDay == null || currentWorkDay.WorkDate != currentDay) {
				currentWorkDay = workDayRepository.GetWorkDay(now);
			}

			if (currentWorkDay == null) {
				currentWorkDay = new WorkDay {
				                             	WorkDate = now.Date,
				                             	StartWork = now,
				                             	EndWork = now,
				                             	LunchTimes = new List<LunchTime>()
				                             };
				workDayRepository.Save(currentWorkDay);
			}
			return currentWorkDay;
		}

		public void Update() {
			workDayRepository.Save(GetCurrentWorkDay());
		}
	}
}